<?php

class Common_model extends CI_Model
{

    var $title = '';
    var $content = '';
    var $date = '';
    var $result = array('error' => 0, 'message' => '', 'content' => '', 'data' => '');

    function __construct()
    {
        parent::__construct();
    }

    /**
     * 校验验证码
     * @param string $code_type
     * @param string $code
     * @return boolean
     */
    public function check_captcha($code_type = 'signin', $code = '')
    {
        $return_code = $this->captcha('signin', 'check', $code);
        if ($return_code == '200') {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * 生成、校验验证码的原始方法
     * @param string $code_type
     * @param string $act
     * @param string $code
     * @return number | image
     */
    public function captcha($code_type = 'signin', $act = 'generate', $code = '')
    {

        $this->load->library('captcha');
        $this->captcha->folder = FCPATH . 'assets/captcha/';
        $this->captcha->width  = 80;
        $this->captcha->height = 28;
        switch ($code_type) {
            case "login":
                $session_word = 'captcha_login';
                break;
            case "signin":
                $session_word = 'captcha_signup';
                break;
            case "findPwd":
                $session_word = 'captcha_findPwd';
                break;
        }
        if ($act == 'generate') {
            @ob_end_clean();
            $this->captcha->session_word = $session_word;
            $this->captcha->generate_image();
        } elseif ($act == 'check') {
            if (empty($code)) {
                $return_code = 204;//无内容，空值
            } else {
                /* 检查验证码 */
                $this->captcha->session_word = $session_word;
                if (!$this->captcha->check_word($code)) {
                    $return_code = 401;//匹配错误
                } else {
                    $return_code = 200;//正确
                }
            }
            return $return_code;
        }
    }

    public function send_sms($mobile, $code_type = 'signup')
    {
        $content = $this->sms_content($code_type, 6);
        $this->load->library('sms');
        $return_code = 1;//$this->sms->send($mobile, $content['string']);
        if ($return_code == 1) {
            $this->session->set_userdata('sms_time', now());
            $this->session->set_userdata('sms_mobile', $mobile);
            $this->session->set_userdata('sms_code', $content['code']);
            //$time = now() + 1800;
            //setcookie('LHY[last_send_sms_time]', now(), $time, $cookie_path, $cookie_domain);
            $cookie = array(
                'name'   => 'last_send_sms_time',
                'value'  => now(),
                'expire' => '1800',
                'domain' => '',//'.some-domain.com',
                'path'   => '/',
                'prefix' => 'lhy_',
                'secure' => TRUE
            );
            $this->input->set_cookie($cookie);
        }
        return $return_code;
    }

    public function verify_sms($sms_code, $code_type = 'signup')
    {
        $serve_code = $this->session->userdata('sms_code');
        if (empty($serve_code)) {
            return 400;//服务端无验证码
        } else {
            if ($serve_code == $sms_code) {
                return 200;//success
            } else {
                return 300;//错误
            }
        }
    }

    /**
     * 获得短信内容
     * @param string $code_type
     * @param number $code_len 验证码长度
     * @param string $code_type all|(num lower upper可以组合)
     * @return string
     */
    private function sms_content($code_type = 'signup', $code_len = 5, $code_type = 'num')
    {
        switch ($code_type) {
            case 'login':
                $content_str = "验证码：%s（用于登录，请勿泄露）如非本人操作，请删除！";
            case 'signup':
                $content_str = "验证码：%s（用于注册，请勿泄露）如非本人操作，请删除！";
            case 'reset_pwd':
                $content_str = "验证码：%s（用于修改密码，请勿泄露）如非本人操作，请删除！";
                break;
            default:
                $content_str = "验证码：%s（老虎游商户平台验证码，三十分钟有效）";
                break;
        }
        $code_string      = random_str($code_len, $code_type);
        $result['string'] = sprintf($content_str, $code_string);
        $result['code']   = $code_string;
        return $result;
    }

    /**
     * 分页的信息加入条件的数组
     *
     * @access  public
     * @return  array
     */
    function page_and_size($filter = array(), $record_count = 0, $page = 1, $page_size = 15)
    {
        $filter['uri'] = site_url($this->router->class);
        if (!isset($filter['page'])) {
            $filter['page'] = $page;
        }
        if (isset($filter['page_size']) && intval($filter['page_size']) > 0) {
            $pager['page_size'] = intval($_REQUEST['page_size']);
        } elseif (isset($_COOKIE['LTPager']['page_size']) && intval($_COOKIE['LTPager']['page_size']) > 0) {
            $pager['page_size'] = $filter['page_size'] = intval($_COOKIE['LTPager']['page_size']);
        } else {
            $pager['page_size'] = $filter['page_size'] = $page_size;
        }
        $pager['record_count'] = $record_count;
        /* page 总数 */
        $page_count          = (!empty($pager['record_count']) && $pager['record_count'] > 0) ? ceil($pager['record_count'] / $pager['page_size']) : 1;
        $page_prev           = ($page > 1) ? $page - 1 : 1;
        $page_next           = ($page < $page_count) ? $page + 1 : $page_count;
        $pager['page_count'] = $page_count;
        $pager['page']       = $page > $pager['record_count'] ? $pager['record_count'] : $page;
        //记录起始
        $pager['start'] = ($pager['page'] - 1) * $pager['page_size'];

        $_pagenum = 10;     // 显示的页码
        $_offset  = 2;       // 当前页偏移值
        $_from    = $_to = 0;  // 开始页, 结束页
        if ($_pagenum > $page_count) {
            $_from = 1;
            $_to   = $page_count;
        } else {
            $_from = $page - $_offset;
            $_to   = $_from + $_pagenum - 1;
            if ($_from < 1) {
                $_to   = $page + 1 - $_from;
                $_from = 1;
                if ($_to - $_from < $_pagenum) {
                    $_to = $_pagenum;
                }
            } elseif ($_to > $page_count) {
                $_from = $page_count - $_pagenum + 1;
                $_to   = $page_count;
            }
        }
        $pager['page_first'] = $page > 1 ? 1 : '';//($page - $_offset > 1 && $_pagenum < $page_count) ? 1 : '';
        $pager['page_prev']  = ($page > 1) ? $page_prev : '';
        $pager['page_next']  = ($page < $page_count) ? $page_next : '';
        $pager['page_last']  = $page < $page_count ? $page_count : '';//($_to < $page_count) ? $page_count : '';
        for ($i = $_from; $i <= $_to; ++$i) {
            $pager['page_number'][$i] = $i;
        }

        $filter['page_count'] = $pager['page_count'];
        $filter['page_size']  = $pager['page_size'];
        $pager['filter']      = $filter;
        return $pager;
    }

    /**
     * 取出消息列表
     * @param unknown $receive_id 接收方id
     * @param unknown $receive_type 接收对象身份：0-系统，1-商家；2-技师；3-用户
     * @param number $send_id 发送方id
     * @param number $send_type 发送对象身份：0-系统，1-商家；2-技师；3-用户
     * @param number $msg_type 消息类型【1-申请，2-关注，3-订单，4-评论】
     * @param number $action_type 消息类型对应状态
     * 1-申请:11-申请绑定，12-申请解绑，110-拒绝绑定，120-拒绝解绑，111-同意绑定，121-同意解绑
     * 2-关注:21-新增关注，22-取消关注
     * 3-订单:31-新订单，32-确认订单，39-完成订单
     */
    public function get_message_list($receive_id, $receive_type, $send_id = 0, $send_type = 0, $msg_type = 0, $action_type = 0, $is_new = 0, $limit = 5)
    {
        $this->db->select('*');
        $this->db->from('messages');
        $this->db->where('receive_id', $receive_id);
        $this->db->where('receive_type', $receive_type);
        if ($send_id > 0) {
            $this->db->where('send_id', $send_id);
            $this->db->where('send_type', $send_type);
        }
        if ($is_new > 0) {
            $this->db->where('is_new', 1);
        }
        if ($msg_type > 0) {
            $this->db->where('msg_type', $msg_type);
        }
        if ($action_type > 0) {
            $this->db->where('action_type', $action_type);
        }
        $this->db->order_by('msg_time', 'desc');
        $this->db->limit($limit);
        $res                    = $this->db->get()->result_array();
        $lan_msg_type           = array('1' => '申请', '2' => '关注', '3' => '订单', '4' => '评论');
        $lan_action_type['11']  = '技师【 %s】 申请绑定！';
        $lan_action_type['12']  = '技师【 %s】申请解绑！';
        $lan_action_type['110'] = '商家【 %s】拒绝了您的绑定请求！';
        $lan_action_type['120'] = '技师【 %s】 拒绝解绑';
        $lan_action_type['21']  = '【%s】关注了你！';
        $lan_action_type['22']  = '【%s】取消了对你的关注！';
        $lan_action_type['31']  = '有新订单啦！订单号： %s ';
        $lan_action_type['32']  = '确认订单';
        $lan_action_type['39']  = '订单[%s]已经完成！';
        $list                   = array();
        foreach ($res as $key => $row) {
            $add_time = local_date("Y-m-d H:i:s", $row['msg_time']);
            switch ($row['msg_type']) {
                case '1':
                    $this->load->model('staff_model');
                    $staff_info        = $this->staff_model->get_info($row['send_id'], 'staff_id, staff_sn, name');
                    $row['staff_info'] = $staff_info;
                    $msg_info          = sprintf("[%s]：" . $lan_action_type[$row['action_type']], $lan_msg_type[$row['msg_type']], $staff_info['staff_sn'] . '号' . $staff_info['name']);
                    break;
                case '2':

                    break;
                case '3':
                    $this->load->model('order_model');
                    $order_info = $this->order_model->get_info($row['order_id'], 'order_sn');
                    $msg_info   = sprintf("[%s]：" . $lan_action_type[$row['action_type']], $lan_msg_type[$row['msg_type']], $order_info['order_sn']);
                    break;;
                default:
                    $msg_info = "系统消息!";
                    break;
            }
            $row['msg_info'] = $msg_info;
            $list[]          = $row;
        }
        return $list;
    }

    /**
     * 取出单条消息
     * @param unknown $receive_id 接收方id
     * @param unknown $receive_type 接收对象身份：0-系统，1-商家；2-技师；3-用户
     * @param number $send_id 发送方id
     * @param number $send_type 发送对象身份：0-系统，1-商家；2-技师；3-用户
     * @param number $msg_type 消息类型【1-申请，2-关注，3-订单，4-评论】
     * @param number $action_type 消息类型对应状态
     */
    public function get_one_message($receive_id, $receive_type, $send_id = 0, $send_type = 0, $msg_type = 0, $action_type = 0, $is_new = 0)
    {
        $this->db->select('*');
        $this->db->from('messages');
        $this->db->where('receive_id', $receive_id);
        $this->db->where('receive_type', $receive_type);
        if ($send_id > 0) {
            $this->db->where('send_id', $send_id);
            $this->db->where('send_type', $send_type);
        }
        if ($msg_type > 0) {
            $this->db->where('msg_type', $msg_type);
        }
        if ($is_new > 0) {
            $this->db->where('is_new', 1);
        }
        if ($action_type > 0) {
            $this->db->where('action_type', $action_type);
        }
        $this->db->order_by('msg_time', 'desc');
        $msg = $this->db->get()->row_array();
        return $msg;
    }

    /**
     * 添加一条系统消息
     * @param unknown $send_id 发送方id
     * @param unknown $send_type 发送对象身份：0-系统，1-商家；2-技师；3-用户
     * @param unknown $receive_id 接收方id
     * @param unknown $receive_type 接收对象身份：0-系统，1-商家；2-技师；3-用户
     * @param unknown $msg_type 消息类型【1-申请，2-关注，3-订单，4-评论】
     * @param unknown $action_type 消息类型对应状态
     * 1-申请:11-申请绑定，12-申请解绑，110-拒绝绑定，120-拒绝解绑，111-同意绑定，121-同意解绑
     * 2-关注:21-新增关注，12-取消关注
     * 3-订单:31-新订单，32-确认订单，39-完成订单
     */
    public function add_new_message($send_id, $send_type, $receive_id, $receive_type, $msg_type, $action_type, $parent_id = 0)
    {
        try {
            $db_data['send_id']      = $send_id;
            $db_data['parent_id']    = $parent_id;
            $db_data['send_type']    = $send_type;
            $db_data['receive_id']   = $receive_id;
            $db_data['receive_type'] = $receive_type;
            $db_data['is_new']       = 1;
            $db_data['msg_type']     = $msg_type;
            $db_data['action_type']  = $action_type;
            $db_data['msg_time']     = gmtime();
            $this->db->insert('messages', $db_data);
            //$this->result['msg_id'] = $this->db->insert_id();
        } catch (Exception $e) {
            $this->result['error']   = 1;
            $this->result['message'] = $e->getMessage();
        }
        return $this->result;
    }
}

?>